import React, { useState, useRef, useEffect } from 'react';
import { sysLogConfig } from '~/API';
import i from '@/index.module.css';
import s from './style.module.css';
import cn from 'classnames';
import { getErrorMessage, isIP } from '@/common/constant';
import { Switch, Dialog, Form, Input, Confirm, Button, Table, Message } from '@knownsec/react-component';
function isRepeat(data, cur) {
  const arr = data.map((item) => item.ip + item.port);
  return arr.filter((item) => item === cur).length ? true : false;
}
export default function SysLog() {
  const [visible, setVisible] = useState(false);
  const [swi, setSwi] = useState(0);
  const [data, setData] = useState([]);
  const [statu, setStatu] = useState(-1);
  const [loading, setLoading] = useState(false);
  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 16 },
  };
  const form = useRef();
  const column = [
    { title: '操作人', key: 'ip', dataIndex: 'ip' },
    { title: '角色', key: 'ip', dataIndex: 'ip' },
    { title: '登录IP', key: 'ip', dataIndex: 'ip' },
    { title: '系统记录', key: 'port', dataIndex: 'port' },
    {
      title: '操作',
      key: 'desc',
      dataIndex: 'desc',
      render: (cur, item) => {
        return (
          <span className={cn(i.mainColor, i.cp)} onClick={() => chageConfig(item.desc.detail)}>
            查看详情
          </span>
        );
      },
    },
  ];
  useEffect(() => {
    getTableData();
  }, []);
  const getTableData = () => {
    setLoading(true);
    sysLogConfig('GET').then((res) => {
      setSwi(res?.data?.switch || 0);
      const d = res?.data?.services || [];
      const narr = d.map((item, index) => {
        item.nid = index;
        return item;
      });
      setLoading(false);
      setData(narr);
    });
  };
  const submitData = () => {
    form.current.validateFields().then((res) => {
      if (isIP(res.ip) <= 0) {
        Message.show({
          type: 'error',
          message: 'IP地址格式错误',
        });
        return;
      }
      if (Number(res.port) !== parseInt(res.port)) {
        Message.show({
          type: 'error',
          message: '端口格式错误',
        });
        return;
      }
      if (isRepeat(data, res.ip + res.port) && statu == -1) {
        Message.show({
          type: 'error',
          message: 'IP地址和端口重复',
        });
        return;
      }
      if (statu < 0) {
        finalData('POST', res);
      } else {
        res.index = statu;
        finalData('PUT', res);
      }
    });
  };
  const deleteData = (id) => {
    Confirm({
      title: '提示',
      pro: true,
      message: <div className={cn(i.tac, i.mb10)}>你确定要删除选中的数据吗？</div>,
      onconfirm: () => {
        sysLogConfig('DELETE', { index: id })
          .then((res) => {
            setVisible(false);
            Message.show({
              type: res.status,
              message: '删除成功',
              onclose() {
                getTableData();
              },
            });
          })
          .catch((err) => Message.show({ type: 'error', message: getErrorMessage(err) }));
      },
    });
  };
  const modifyData = (id) => {
    setStatu(id);
    const newArr = data.filter((item) => item.nid === id);
    form.current.setFieldsValue(...newArr);
    setVisible(true);
  };
  const chageConfig = () => {
    setStatu(-1);
    setVisible(true);
  };
  const finalData = (method, data) => {
    sysLogConfig(method, data)
      .then((res) => {
        setVisible(false);
        Message.show({
          type: res.status,
          message: '设置成功',
          onclose() {
            getTableData();
            form.current.resetFields();
            setVisible(false);
          },
        });
      })
      .catch((err) => Message.show({ type: 'error', message: getErrorMessage(err) }));
  };
  const changeItem = (newItem) => {
    const values = Object.keys(newItem).reduce((total, key) => {
      let value;
      value = newItem[key].value;
      total[key] = value;
      return total;
    }, {});
    form.current.setFieldsValue(values);
  };
  
  return (
    <div className={cn(i.pt15, i.pl20, i.pr20)}>
      <div>
        <Table columns={column} data={data} tableLoading={loading} loadingLabel="" />
      </div>
      <Dialog
        title="服务器配置"
        className={s.w500}
        visible={visible}
        onsubmit={submitData}
        onhide={() => {
          form.current.resetFields();
          setVisible(false);
        }}
      >
        <div className={cn(s.pl60, i.pr20)}>
          <Form ref={form} {...layout} onValuesChange={(it) => changeItem(it)}>
            <Form.Item
              label="服务器地址"
              name="ip"
              rules={[{ required: true, message: '服务器地址不能为空' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="服务器端口"
              name="port"
              rules={[{ required: true, message: '服务器端口不能为空' }]}
            >
              <Input />
            </Form.Item>
          </Form>
        </div>
      </Dialog>
    </div>
  );
}
